﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using BlammoNet.Enum;
using BlammoNet.Interfaces;
using DotCache.Interfaces;
#endregion

namespace DotCache.BaseClass
{
    /// <summary>
    /// Cache base class
    /// </summary>
    public class Cache:ICache
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public Cache()
        {
            try
            {
                InternalCache = new Dictionary<string, ICacheItem>();
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        #endregion

        #region Functions

        public T Get<T>(string Key)
        {
            try
            {
                lock (InternalCache)
                {
                    return (T)InternalCache[Key].Value;
                }
            }
            catch(Exception e) 
            {
                LogError(e);
                throw;
            }
        }

        public bool Exists(string Key)
        {
            try
            {
                return InternalCache.ContainsKey(Key);
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        public void Add(string Key, object Value)
        {
            try
            {
                if (Exists(Key))
                {
                    lock (InternalCache[Key])
                    {
                        if (Exists(Key))
                        {
                            InternalCache[Key].Update();
                            InternalCache[Key].Value = Value;
                        }
                    }
                    if (Configuration.EnableLogging)
                        Log.LogMessage("{0} updated", MessageType.Debug, Key);
                }
                else
                {
                    lock (InternalCache)
                    {
                        if (!Exists(Key))
                        {
                            InternalCache.Add(Key, new CacheItem(Key, Value, new TimeSpan(0, 0, 0), this));
                        }
                    }
                    if (Configuration.EnableLogging)
                        Log.LogMessage("{0} added", MessageType.Debug, Key);
                }
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        public void Add(string Key, object Value, TimeSpan Expiration)
        {
            try
            {
                if (Exists(Key))
                {
                    lock (InternalCache)
                    {
                        if (Exists(Key))
                        {
                            InternalCache[Key].Update(Expiration);
                            InternalCache[Key].Value = Value;
                        }
                    }
                    if (Configuration.EnableLogging)
                        Log.LogMessage("{0} updated", MessageType.Debug, Key);
                }
                else
                {
                    lock (InternalCache)
                    {
                        if (!Exists(Key))
                        {
                            InternalCache.Add(Key, new CacheItem(Key, Value, Expiration, this));
                        }
                    }
                    if (Configuration.EnableLogging)
                        Log.LogMessage("{0} added", MessageType.Debug, Key);
                }
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        public void Remove(string Key)
        {
            try
            {
                if (InternalCache.ContainsKey(Key))
                {
                    lock (InternalCache)
                    {
                        if (InternalCache.ContainsKey(Key))
                        {
                            InternalCache[Key].Dispose();
                            InternalCache.Remove(Key);
                        }
                    }
                    if (Configuration.EnableLogging)
                        Log.LogMessage("{0} removed", MessageType.Debug, Key);
                }
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        public void Clear()
        {
            try
            {
                Dispose();
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        public IEnumerator<object> GetEnumerator()
        {
            foreach (string Key in this.InternalCache.Keys)
            {
                this.InternalCache[Key].Update();
                yield return this.InternalCache[Key].Value;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            foreach (string Key in this.InternalCache.Keys)
            {
                this.InternalCache[Key].Update();
                yield return this.InternalCache[Key].Value;
            }
        }

        public void Dispose()
        {
            try
            {
                if (Configuration.EnableLogging)
                    Log.LogMessage("Cache being disposed", MessageType.Debug);
                lock (InternalCache)
                {
                    foreach (string Item in InternalCache.Keys)
                    {
                        InternalCache[Item].Dispose();
                    }
                    InternalCache.Clear();
                }
            }
            catch (Exception e)
            {
                LogError(e);
                throw;
            }
        }

        #endregion

        #region Private Functions

        private void LogError(Exception e)
        {
            try
            {
                if (Configuration.EnableLogging)
                    Log.LogMessage("Error Occurred: {0}", MessageType.Error, e.ToString());
            }
            catch { }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Internal cache
        /// </summary>
        protected Dictionary<string, ICacheItem> InternalCache { get; set; }

        public ILog Log { get; set; }

        public Config.Config Configuration { get; set; }

        public ICollection<string> Keys
        {
            get
            {
                try
                {
                    lock (InternalCache)
                    {
                        return InternalCache.Keys;
                    }
                }
                catch(Exception e)
                {
                    LogError(e);
                    throw; 
                }
            }
        }

        public int Count
        {
            get 
            { 
                try 
                { 
                    return InternalCache.Count;
                }
                catch (Exception e)
                {
                    LogError(e);
                    throw;
                }
            }
        }

        public object this[string Key]
        {
            get
            {
                try
                {
                    if (Exists(Key))
                    {
                        InternalCache[Key].Update();
                        return InternalCache[Key].Value;
                    }
                    return null;
                }
                catch (Exception e)
                {
                    LogError(e);
                    throw;
                }
            }
            set
            {
                try
                {
                    Add(Key, value);
                }
                catch (Exception e)
                {
                    LogError(e);
                    throw;
                }
            }
        }

        #endregion

        #region Public Overridden Functions

        /// <summary>
        /// Outputs the contents of the cache
        /// </summary>
        /// <returns>An HTML formatted table containing the cache's contents</returns>
        public override string ToString()
        {
            StringBuilder Builder = new StringBuilder();
            Builder.Append("<table><tr><th>Key</th><th>Value</th></tr>");
            foreach (string Key in this.Keys)
            {
                Builder.Append("<tr><td>").Append(Key).Append("</td><td>").Append(this[Key].ToString()).Append("</td></tr>");
            }
            Builder.Append("</table>");
            return Builder.ToString();
        }

        #endregion
    }
}